﻿// For an introduction to the Page Control template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232511
(function () {
    "use strict";

    WinJS.UI.Pages.define("/pages/selectTipId/selectTipId.html", {
        // This function is called whenever a user navigates to this page. It
        // populates the page elements with the app's data.
        ready: function (element, options) {
            //$("#autoTipIdEditText").val();
            var userId = options.userId;
            var merchantId = options.merchantId;

            // Generate Tip ID.
            generateTipId(userId);
        },

        updateLayout: function (element, viewState, lastViewState) {
            /// <param name="element" domElement="true" />
            /// <param name="viewState" value="Windows.UI.ViewManagement.ApplicationViewState" />
            /// <param name="lastViewState" value="Windows.UI.ViewManagement.ApplicationViewState" />

            // TODO: Respond to changes in viewState.
        },

        unload: function () {
            // TODO: Respond to navigations away from this page.
        }
    });

    function generateTipId(userId) {
        WinJS.xhr({
            url: HOST_NAME + "/getAutoTipID/?user_id=" + userId,
        }).then(
            function onComplete(result) {
                // Check if API call is successful.
                if (result.status === 200) {
                    console.log(result.responseText);

                    // Parse xhr to JSON.
                    var response = JSON.parse(result.response);
                    var isSuccessful = response.is_execution_successful;

                    // Check result code.
                    if (isSuccessful == true) {
                        var tipId = response.data;
                        $("#autoTipIdEditText").val(tipId);
                        return result;
                    }
                }
            },
            function onError(error) {
                console.log("generateTipId::error: " + error.message);
            }
        )
    }
})();
